import { stringify } from 'querystring';
import type { Reducer, Effect } from 'umi';
import { history } from 'umi';

import { fakeAccountLogin ,logout} from '@/services/login';
import { getPageQuery } from '@/utils/utils';
import {message} from "antd";

export type StateType = {
};

export type LoginModelType = {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
};

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      //发送请求，登录
      const response = yield call(fakeAccountLogin, payload);

      if(response.status === undefined){
        message.success('登录成功')

        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
        //跳转到首页
        history.replace('/')
      }

    },

    *logout(_,{call}) {
      const load = message.loading('退出中...')
      const response = yield call(logout)
      if(response.status === undefined){
        //删除本地储存

        localStorage.clear()
        message.success('退出成功')
        history.replace('/login')

      }

      load()
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      //将token存到localStorage中
      localStorage.setItem("access_token",payload.access_token)

      return {
        ...state
      };
    },
  },
};

export default Model;
